from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                           QLabel, QLineEdit, QPushButton, QProgressBar, 
                           QFileDialog, QMessageBox)
from PyQt6.QtGui import QIntValidator
from ..modbus_client import ModbusClient     # 修改导入路径
from ..firmware_updater import FirmwareUpdater  # 修改导入路径

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        
    def setup_ui(self):
        # 创建主窗口布局
        central = QWidget()
        layout = QVBoxLayout(central)
        
        # IP地址输入，默认值设为设备IP
        ip_layout = QHBoxLayout()
        ip_layout.addWidget(QLabel("设备IP:"))
        self.ip_edit = QLineEdit("192.168.1.99")
        ip_layout.addWidget(self.ip_edit)
        layout.addLayout(ip_layout)
        
        # 端口输入，默认为4001
        port_layout = QHBoxLayout()
        port_layout.addWidget(QLabel("端口:"))
        self.port_edit = QLineEdit("4001")
        self.port_edit.setValidator(QIntValidator(1, 65535))
        port_layout.addWidget(self.port_edit)
        layout.addLayout(port_layout)
        
        # 状态显示
        self.status_label = QLabel("就绪")
        layout.addWidget(self.status_label)
        
        # 文件选择
        file_layout = QHBoxLayout()
        self.file_edit = QLineEdit()
        file_layout.addWidget(self.file_edit)
        self.browse_btn = QPushButton("浏览...")
        self.browse_btn.clicked.connect(self.browse_file)
        file_layout.addWidget(self.browse_btn)
        layout.addLayout(file_layout)
        
        # 进度条
        self.progress = QProgressBar()
        layout.addWidget(self.progress)
        
        # 更新按钮
        self.update_btn = QPushButton("开始更新")
        self.update_btn.clicked.connect(self.start_update)
        layout.addWidget(self.update_btn)
        
        self.setCentralWidget(central)
        self.setWindowTitle("固件更新工具")
        self.setFixedSize(400, 250)
        
    def browse_file(self):
        filename, _ = QFileDialog.getOpenFileName(
            self,
            "选择固件文件",
            "",
            "Bin Files (*.bin);;All Files (*.*)"
        )
        if filename:
            self.file_edit.setText(filename)
            
    def start_update(self):
        if not self.file_edit.text():
            QMessageBox.warning(self, "错误", "请选择固件文件")
            return
            
        ip = self.ip_edit.text()
        port = int(self.port_edit.text())
        
        # 禁用更新按钮
        self.update_btn.setEnabled(False)
        self.status_label.setText("正在更新...")
        
        try:
            client = ModbusClient(ip, port)
            client.connect()
            
            updater = FirmwareUpdater(client)
            updater.update_firmware(
                self.file_edit.text(),
                lambda p: self.progress.setValue(int(p))
            )
            
            QMessageBox.information(self, "成功", "固件更新完成")
            self.status_label.setText("更新完成")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"更新失败: {str(e)}")
            self.status_label.setText("更新失败")
            
        finally:
            self.update_btn.setEnabled(True)
